//
//扩展:OC中有人使用try catch 吗?为什么
//ARC开发,编译器自动添加retain/release/autorelease
//如果用try.catch不平衡,就会出现内存泄漏
//

/*
 使用代理传递消息为了实在控制器和视图之间解耦,让试图能够被多个控制器复用.
 */
//  WBBaseViewController.swift
//  Swift_sina
//
//  Created by TFB_WGP on 2017/8/16.
//  Copyright © 2017年 TFB_WGP. All rights reserved.
//

import UIKit

//面试题:OC中支持多继承吗?如果不支持,如何替代?答案:使用协议代替
//Swift的写法类似于多继承
//1.extension中不能有属性 2.extension不能重写父类本类的方法(父类方法写在extension中,子类也要写在extension中),扩展是对类的扩展
class WBBaseViewController: UIViewController {
    
    var visitorInfo: [String:String]?
    
    
    //用户如果没有登录,就不创建加载
    var tableView: UITableView?
    /// 刷新控件
    var refreshController: UIRefreshControl?
    /// 是否上拉加载
    var isPullUp: Bool = false
    
    
    //自定义导航条
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 64))
    //自定义的导航条目
    lazy var navItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        NetworkRequest.sharedInstance.isLogin ? loadData() : ()
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess(notifition:)), name: NSNotification.Name(rawValue: "WBUserLoginSuccessNotifiction"), object: nil)
    }
    
    override var title: String?{
        didSet{
            navItem.title = title
        }
    }
    
    /// 登陆成功处理
    @objc func loginSuccess(notifition: NSNotification){
        //重新设置View,重新执行loadView方法
        view = nil
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    //加载数据源
    func loadData() {
        refreshController?.endRefreshing()
    }
    
   func setLeftBarButtonItemWithSpace(arr: [UIBarButtonItem]) -> Void {
        let navigationSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        navigationSpacer.width = -5;
        var items: [UIBarButtonItem] = [navigationSpacer]
        for barButtonItem in arr {
            items.append(barButtonItem)
        }
        navItem.leftBarButtonItems = items
    }
    
    func setRightBarButtonItemWithSpace(arr: [UIBarButtonItem]) -> Void {
        let navigationSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        navigationSpacer.width = -5;
        var items: [UIBarButtonItem] = []
        items.append(navigationSpacer)
        for barButtonItem in arr {
            items.append(barButtonItem)
        }
        navItem.rightBarButtonItems = items
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension WBBaseViewController{
    @objc func loginBtnDidClick(){
    
//        发送登录通知
        NotificationCenter.default.post(name: NSNotification.Name(WBUserShouldLoginNotifiction), object: nil)
    }
    
    @objc func registerBtnDidClick(){
        print("注册")
    }
    
    @objc func findBtnDidClick(){
        print("找感兴趣得人")
    }
}

extension WBBaseViewController{
    fileprivate func setupUI() -> Void {
        
        //取消自动缩颈-如果隐藏了导航浪,会缩进20
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.white
        
        //添加导航条
        view.addSubview(navigationBar)
        navigationBar.items = [navItem]
        
        //设置navBar的渲染颜色
        navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray,NSFontAttributeName:UIFont.systemFont(ofSize: titleFont)]
        
        //判断是否登录
        NetworkRequest.sharedInstance.isLogin ? setupTableView() : setupVisitorView()
    }
    
    /// 访客视图
     func setupVisitorView(){
        let visitorView = WBVisitorView(frame: view.frame)
        
        view.insertSubview(visitorView, belowSubview: navigationBar)
        visitorView.visitorInfo = visitorInfo
        
        visitorView.loginBtn.addTarget(self, action: #selector(loginBtnDidClick), for: .touchUpInside)
        visitorView.registerBtn.addTarget(self, action: #selector(registerBtnDidClick), for: .touchUpInside)
        visitorView.findBtn.addTarget(self, action: #selector(findBtnDidClick), for: .touchUpInside)
    }
    
    /// 设置tableView
    func setupTableView(){
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView?.delegate = self
        tableView?.dataSource = self
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        //设置内容缩进
        tableView?.contentInset = UIEdgeInsetsMake(navigationBar.bounds.height, 0, tabBarController?.tabBar.bounds.height ?? 49, 0)
        
        tableView!.scrollIndicatorInsets = tableView!.contentInset
        
        //        添加刷新控件
        refreshController = UIRefreshControl()
        tableView?.addSubview(refreshController!)
        //        添加监听方法
        refreshController?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
}

extension WBBaseViewController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let row =  indexPath.row
        let section = tableView.numberOfSections - 1
//        最后一组的行数
        let count = tableView.numberOfRows(inSection: section)
        if row == (count - 1) && !isPullUp {
            
            print("上拉刷新")
            isPullUp = true
            
//            开始加载数据
            loadData()
        }
    }
}
